#!/usr/bin/python # for editor

import os.path
import sys

Import('WARN_CFLAGS env bin_dir inc_dir lib_dir')

TARGET_BUILD    = 'runtime'
TARGET_INSTALL  = 'runtime-install'

OBJC            = './compiler/sobjc4gcc'
OBJCFLAGS       = '-O2 -g --ansi --pedantic %s' % WARN_CFLAGS

INCLUDES        = 'sobjc.h'
INCLUDES_SOBJC  = 'sobjc/protocol.h sobjc/class.h sobjc/method.h sobjc/runtime.h sobjc/object.h sobjc/selector.h sobjc/ivar.h sobjc/proto.h sobjc/log.h'
INCLUDES_CLASS  = 'sobjc/classes/Object.h sobjc/classes/ConstantString.h'
SRCS            = 'selector.c class.c ivar.c method.c protocol.c object.c runtime.c log.c'

OBJC_SRC_DIR    = 'classes'
OBJC_SRC_NAMES  = 'Object.m ConstantString.m'
OBJC_SRCS       = []
for name in Split(OBJC_SRC_NAMES):
    OBJC_SRCS.append(os.path.join(OBJC_SRC_DIR, name))

LIB_PATH            = ['.', '../commons']
LIB_SOBJC_COMMONS   = 'sobjc-commons'
LIB_SOBJC           = 'sobjc'
LIB_SOBJC_PROF      = 'sobjc-profile'

env = env.Clone(OBJC=OBJC)
env.Prepend(OBJCFLAGS=OBJCFLAGS)
for h in Split(INCLUDES) + Split(INCLUDES_SOBJC) + Split(INCLUDES_CLASS):
    env.Command(os.path.join(inc_dir, h), h,
               [Copy('$TARGET', '$SOURCE'), Chmod('$TARGET', 0644)])
env.Alias(TARGET_INSTALL, lib_dir)
env.Alias(TARGET_INSTALL, os.path.join(inc_dir, 'sobjc'))

def build(env):
    if env.is_targeted(TARGET_BUILD, TARGET_INSTALL):
        build_srcs(env)
        if env['PROFILE']:
            build_profile_srcs(env)

def build_srcs(env):
    if env['STATIC']:
        clslib = []
        for src in OBJC_SRCS:
            clslib.append(env.ObjCStaticObject(src))
        lib = env.Library(LIB_SOBJC, Split(SRCS)+clslib,
                LIBS=[LIB_SOBJC_COMMONS], LIBPATH=LIB_PATH)
    else:
        clslib = []
        for src in OBJC_SRCS:
            clslib.append(env.ObjCSharedObject(src))
        lib = env.SharedLibrary(LIB_SOBJC, Split(SRCS)+clslib,
                LIBS=[LIB_SOBJC_COMMONS], LIBPATH=LIB_PATH)
    env.Install(lib_dir, lib)

def build_profile_srcs(env):
    env = env.Clone(CPPDEFINES={'OBJC_PROFILE':1})
    env.Replace(OBJSUFFIX='-profile.o')
    env.Replace(SHOBJSUFFIX='-profile.os')
    if env['STATIC']:
        lib = env.Library(LIB_SOBJC_PROF, Split(SRCS),
                LIBS=[LIB_SOBJC_COMMONS], LIBPATH=LIB_PATH)
    else:
        lib = env.SharedLibrary(LIB_SOBJC_PROF, Split(SRCS),
                LIBS=[LIB_SOBJC_COMMONS], LIBPATH=LIB_PATH)
    env.Install(lib_dir, lib)

if '-h' not in sys.argv:
  build(env)

